package com.rytong.tools.ui;

import com.rytong.tools.R;
import com.rytong.tools.utils.Utils;

import android.app.Activity;
import android.app.Dialog;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
/**
 * 自定义键盘,字母和数字每次弹出时随机变化
 * 
 * @author cheng.li@rytong.com
 * 
 */
public class LPKeyBoard implements OnClickListener, OnTouchListener {
	private final char[] keys = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 
			'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o',
			'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c',
			'v', 'b', 'n', 'm' };

	private final String[] keys2 = { "[", "]", "{", "}", "#", "%", "^", "*", "+", "=",
			"_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•", 
			"-", "/", ":", ";", "(", ")", "$", "&", "@", "\"",
			".", ",", "?", "!", "'", "", "" };

	private static final String TAG = "-----RandomKeyBoard-----";

	private ImageButton shiftIB, delIB;
	private Button[] keyBtns = new Button[37];
	private Button keyNumber,keyConfirm; /*keyBtn0,keyBtn1*/ 

	private BaseView mContext;
	private boolean isShift = false;
	private boolean isNumber = false;

	private LinearLayout mLayout;
	private EditText mTextField;
	public Dialog mDialog;

	private int[] aRandom,nRandom;

	public LinearLayout mRootView;
	public LPKeyBoard(Activity context, EditText tf) {
		mContext = (BaseView)context;
		mTextField = tf;
	}

	public void getInstance() {
		LayoutInflater flater = mContext.getLayoutInflater();
		mRootView = (LinearLayout) flater.inflate(R.layout.qwerty, null);

		//shift键和Alt键
		shiftIB = (ImageButton) mRootView.findViewById(R.id.keyshift);
		shiftIB.setOnClickListener(this);
		//删除键
		delIB = (ImageButton) mRootView.findViewById(R.id.keydel);
		delIB.setOnClickListener(this);

		//切换数字字母
		keyNumber = (Button) mRootView.findViewById(R.id.keynumber);
		keyNumber.setOnClickListener(this);
		
		if (isNumber) {
			keyNumber.setText("ABC");
		} else {
			keyNumber.setText("@/#");
			shiftIB.setImageResource(R.drawable.sym_keyboard_shift);
		}

		//确定
		keyConfirm = (Button)mRootView.findViewById(R.id.confirm);
		keyConfirm.setOnClickListener(this);

		int size = keyBtns.length;
		for (int i = 0; i < size; i++) {
			if (i <= 29) {
				keyBtns[i] = (Button) mRootView.findViewById(R.id.key0 + i);
			} else if(i > 29){
				keyBtns[i] = (Button) mRootView.findViewById(R.id.key0 + i + 1);
				if (isNumber && i > 34) {
					keyBtns[i].setVisibility(View.GONE);
				}
			}
			keyBtns[i].setOnTouchListener(this);
		}

		keyBtns[28].measure(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		mLayout = (LinearLayout) keyBtns[24].getParent();
		mLayout.setPadding(keyBtns[28].getMeasuredWidth() / 2, 0,
				keyBtns[28].getMeasuredWidth() / 2, 0);

		//26个随机数，字母
		aRandom = this.getRandomNumber(36);
		//10个随机数，数字
		nRandom = this.getRandomNumber(10);

		if(mTextField.getInputType() >0 && mTextField.getInputType() == InputType.TYPE_CLASS_NUMBER){
			isNumber = true;
			setNumberKeys();
		}else{
			setABCKeys();			
		}
	}

	// 对字母键过滤并赋值
	private void setABCKeys() {
		keyBtns[29].setVisibility(View.GONE);
		mLayout.setPadding(keyBtns[28].getMeasuredWidth() / 2, 0,
				keyBtns[28].getMeasuredWidth() / 2, 0);
		for (int i = 0; i < keyBtns.length; i++) {
			int m = i;
			if (i >= 29) {
				m = m - 1;
			}

			if (isShift) {
				keyBtns[i].setText(String.valueOf(keys[aRandom[m]]).toUpperCase());
			} else {
				keyBtns[i].setText(String.valueOf(keys[aRandom[m]]));
			}
		}
	}

	// 字符和数字赋值
	private void setNumberKeys() {
		keyBtns[9].setVisibility(View.VISIBLE);
		mLayout.setPadding(0, 0, 0, 0);
		for (int i = 0; i < keyBtns.length; i++) {
//			if (!isShift) {
//				if (i < 10) {
//					if (i == 9) {
//						keyBtns[i].setText(nRandom[0] + "");
//					} else {
//						keyBtns[i].setText(nRandom[i + 1] + "");
//					}
//				} 
//				else {
//					keyBtns[i].setText(keys1[i - 10]);
//				}
//			} else {
				keyBtns[i].setText(keys2[i]);
//			}
		}
	}

	//产生随机数
	public int[] getRandomNumber(int limit) {
		int[] result = new int[limit];
		for (int i = 0; i < limit; i++) {
			result[i] = i;
		}
//		int w;
//		Random rand = new Random();
//		for (int i = limit - 1; i > 0; i--) {
//			w = rand.nextInt(i);
//			int t = result[i];
//			result[i] = result[w];
//			result[w] = t;
//		}
		return result;
	}

	// 输入内容
	private void appendBuffer(Button v) {
		int cursor = mTextField.getSelectionEnd();
		if (mContext.maxSize == 0) {
			//此种方式是为了输入内容时最后一个字符回显一秒(仅用于密码，非明文显示)
			mTextField.getText().insert(cursor, v.getText());
			mTextField.setSelection(mTextField.getSelectionEnd());
		} else if (cursor <= (mContext.maxSize - 1)) {
			//此种方式是为了输入内容时最后一个字符回显一秒(仅用于密码，非明文显示)
			mTextField.getText().insert(cursor, v.getText());
			mTextField.setSelection(mTextField.getSelectionEnd());
		}
		Utils.LogD(TAG + "append", "" + mTextField.getText());
	}

	// 删除内容
	private void deleteBuffer() {
		StringBuffer inputBuffer = new StringBuffer();
		String temp = mTextField.getText().toString();
		if (null != temp && !"".equalsIgnoreCase(temp)) {
			inputBuffer = new StringBuffer(temp);
			mTextField.setSelection(inputBuffer.length());
		}

		if (null != inputBuffer && inputBuffer.length() > 0) {
			inputBuffer = inputBuffer.deleteCharAt(inputBuffer.length() - 1);
		}
		mTextField.setText(inputBuffer.toString());
		mTextField.setSelection(inputBuffer.length());
		Utils.LogD(TAG + "delete", "->" + mTextField.getText());

	}

	// 得到这个window高度
	public int getHeight() {
		return keyBtns[28].getMeasuredHeight() * 5;
	}

	/*private void showPopWindow(View v, String str) {
		// TODO Auto-generated method stub
		mTextView.setText(str);

		// 得到View的在当前窗口中的坐标x,y
		int[] location = new int[2];
		v.getLocationInWindow(location);

		mTextView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		if (null != popWindow && !popWindow.isShowing()) {
			int x = location[0] - (popWindow.getWidth() - v.getWidth()) / 2;
			int y = location[1] - mTextView.getMeasuredHeight();
			popWindow.showAtLocation(v, Gravity.AXIS_X_SHIFT, x, y);
		}
	}*/

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.keyshift) {
			if (isShift) {
				isShift = false;
			} else {
				isShift = true;
			}
			if (isNumber) {
				setNumberKeys();
			} else {
				setABCKeys();
			}
		} else if (id == R.id.keydel) {
			deleteBuffer();
		} else if (id == R.id.keynumber) {
			isShift = false;
			if (!isNumber) {
				isNumber = true;
				mRootView.removeAllViews();
				mRootView.invalidate();
				getInstance();
				keyNumber.setText("ABC");
				mRootView.findViewById(R.id.key29).setVisibility(View.VISIBLE);
				mDialog.setContentView(mRootView);
				shiftIB.setClickable(false);
				setNumberKeys();
			} else {
				isNumber = false;
				mRootView.removeAllViews();
				mRootView.invalidate();
				getInstance();
				keyNumber.setText("@/#");
				mRootView.findViewById(R.id.key29).setVisibility(View.GONE);
				mDialog.setContentView(mRootView);
				shiftIB.setImageResource(R.drawable.sym_keyboard_shift);
				setABCKeys();
			}
		}else if(id == R.id.confirm){
			if(null != mDialog && mDialog.isShowing()){
				mDialog.dismiss();
			}
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			//Button btn = (Button) v;
			//			showPopWindow(btn, btn.getText().toString());
			break;
		case MotionEvent.ACTION_UP:
			//			if (null != popWindow && popWindow.isShowing()) {
			//				popWindow.dismiss();
			//			}
			appendBuffer((Button) v);
			break;
		}
		return false;
	}
}